class Solution {
public:
    int longestPalindrome(string word1, string word2) {
        string s = word1 + word2;
        int n=s.size();
        if(n==0)  return 0;

        vector<vector<int>> dp(n,vector<int>(n,0));

        for(int i=0;i<n;i++){
            dp[i][i]=1;
        }

        for(int len=2;len<=n;len++){
            for(int i=0;i<=n-len;i++){
                int j = i+len-1;
                if(s[i]==s[j]){
                    dp[i][j]=dp[i+1][j-1]+2;
                }else{
                    dp[i][j]=max(dp[i+1][j],dp[i][j-1]);
                }
            }
        }
        int res = 0;
        for (int i = 0, t = word1.size(); i < t; ++i) {
            for (int j = word2.size() - 1; j >= 0; --j) {
                if (word1[i] == word2[j]) {
                    res = max(res, dp[i][t + j]);
                    break;
                }
            }
        }
        return res;
    }
};
